
package com.compuvest.web;

// <editor-fold defaultstate="collapsed" desc="import">
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
// </editor-fold>

public final class SessionEvent implements HttpSessionListener {

//    private boolean makeCust = false;

// <editor-fold defaultstate="collapsed" desc="sessionCreated()">

    public synchronized void sessionCreated(HttpSessionEvent event) {

        HttpSession session = event.getSession();
        try {

            // get basket from DB
//            SQLBean sb = (SQLBean)session.getServletContext().getAttribute("sb");
//            if(sb == null) {
//		System.out.println("SessionEvent::sessionCreated:sb=null");
//            }
            // restore old customer basket
//            Basket basket = sb.getBasket(session.getId());

            session.setAttribute("basket", new Basket());
        }
        catch(Exception ex) { System.out.println("SessionEvent::sessionCreated:\n" + ex); }
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="sessionDestroyed()">

    public synchronized void sessionDestroyed(HttpSessionEvent event) {

        HttpSession session = event.getSession();
        try {

            SQLBean sb = (SQLBean)session.getServletContext().getAttribute("sb");
            if(sb == null) {
		System.out.println("SessionEvent::sessionDestroyed:sb=null");
                return;
            }

            Basket basket = (Basket)session.getAttribute("basket");
            // save basket
            if(basket.notEmpty()) {
                sb.setBasket(basket, session.getId());
            }

            Customer cust = basket.getCustomer();
            if(cust != null && cust.getCustomerID() == 0) {

                Mail mail = (Mail)session.getServletContext().getAttribute("mail");
                if(mail == null) {
                    System.out.println("SessionEvent::sessionDestroyed:mail=null");
                    return;
                }

//              mail.sendLostCustomerDetailToMe(basket, makeCust);

                // write down for statistic
//              if(makeCust = !makeCust) {

                // send email to lost customer
                mail.sendEmailToLostCustomerDetail(basket);

                // create new customer
                sb.updateCustomer(cust, basket.getCompuvestCookies().getIPAddress());

//              }
            }

            // delete
            session.removeAttribute("basket");
        }
        catch(Exception ex) { System.out.println("SessionEnvet::sessionDestroyed:\n" + ex); }

    }
// </editor-fold>

}
